package initialize

import (
	"fmt"
	"gin-admin/global"
	"os"

	"github.com/fsnotify/fsnotify"
	"github.com/spf13/viper"
)

func configViper[T any](baseConfigPat string, envConfigPath string, viperStruct T) *viper.Viper {
	v := viper.New()
	v.SetConfigFile(baseConfigPat)
	v.SetConfigType("yaml")
	if err := v.ReadInConfig(); err != nil {
		panic(fmt.Errorf("读取基本配置文件失败: %s", err))
	}

	if envConfigPath != "" {
		envV := viper.New()
		envV.SetConfigFile(envConfigPath)
		envV.SetConfigType("yaml")
		if err := envV.ReadInConfig(); err != nil {
			panic(fmt.Errorf("读取环境配置文件失败: %s", err))
		} else {
			if err := v.MergeConfigMap(envV.AllSettings()); err != nil {
				fmt.Printf("警告: 合并环境配置文件失败: %s\n", err)
			}
		}
	}

	v.WatchConfig()
	v.OnConfigChange(func(in fsnotify.Event) {
		fmt.Println("监听到配置文件发生变化: ", in.Name)
		if err := v.Unmarshal(viperStruct); err != nil {
			fmt.Println("配置文件解析失败: ", err)
		}
	})
	if err := v.Unmarshal(viperStruct); err != nil {
		fmt.Println("配置文件解析失败: ", err)
	}
	return v
}

func InitializeViper() {
	fmt.Println("Viper Service Starting...")
	baseConfig := "config/yaml/config.yaml"
	env := os.Getenv("ENV")
	if env == "" {
		env = "development"
	}

	var envConfigPath string
	switch env {
	case "development":
		envConfigPath = "config/yaml/config.dev.yaml"
	case "production":
		envConfigPath = "config/yaml/config.prod.yaml"
	default:
		envConfigPath = "config/yaml/config.dev.yaml"
	}
	configViper(baseConfig, envConfigPath, &global.GA_CONFIG)
}
